#!/bin/bash

# SVN specific:
#---------------
# $Author: simonbaev $
# $LastChangedDate: 2010-02-22 20:19:39 -0500 (Mon, 22 Feb 2010) $
# $Revision: 8 $
#

for file in *.cue; do
	base=$(basename "$file" .cue)
	temp=$$.cue
	cp "$file" "$temp"
	encoding=$(file --mime-encoding "$temp" | cut -d" " -f2)
	rm $temp
	if [ -f "$base.ape" ] && [ $encoding = "utf-8" -o $encoding = "us-ascii" ]; then
		status="One of the steps failed"
		cuebreakpoints "$base.cue" | shnsplit -o flac "$base.ape" &&\
		cuetag "$base.cue" split-track*.flac &&\
		for a in *.flac; do
			ARTIST=`metaflac "$a" --show-tag=ARTIST | sed s/.*=//g`
			TITLE=`metaflac "$a" --show-tag=TITLE | sed s/.*=//g`
			TRACKNUMBER=`metaflac "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
			mv "$a" "`printf %02g $TRACKNUMBER`-$TITLE.flac"
		done &&\
		status="OK"
	else
		status="Either APE file is missing or CUE file has improper (non-UTF8 or non-US-ASCII) encoding"
	fi
	printf "%-30s%s\n" "$base.cue:" "$status"
done

